package com.cms.work.controller.sys;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cms.work.core.SimpleResponse;
import com.cms.work.core.controller.BaseController;
import com.cms.work.entity.enums.CommonEnum.UserStatusEnum;
import com.cms.work.entity.sys.SysUser;
import com.cms.work.entity.sys.vo.ResetPasswordVO;
import com.cms.work.entity.sys.vo.SysUserRoleVo;
import com.cms.work.service.sys.ISysRoleService;
import com.cms.work.service.sys.ISysUserService;
import com.github.pagehelper.PageInfo;

/**
 * <p>
 * Title: SysUserController
 * </p>
 * <p>
 * Description: 用户控制层
 * </p>
 * <p>
 * Email: yuyue_qty@163.com
 * </p>
 * 
 * @author 晴天雨
 * @date 2016年11月23日下午11:01:02
 * @version 1.0
 */
@Controller
@RequestMapping("/sys")
public class SysUserController extends BaseController<SysUser> {

	private static final Logger logger = LoggerFactory
			.getLogger(SysUserController.class);

	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysRoleService sysRoleService;

	@RequestMapping(value = "/queryUserPage", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> queryPage(HttpServletRequest request, SysUser sysUser) {
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> result = new HashMap<String, Object>();

		try {
			//映射实体属性和表字段之间的关系
			params.put("id", "id");
			params.put("userName", "user_name");
			params.put("loginCode", "login_code");
			params.put("status", "status");

			//封装排序数据
			params.put("orderBy",
					params.get(request.getParameter("orderColumn")));
			params.put("orderDir", request.getParameter("orderDir"));

			//封装分页数据
			Integer pageNum = (request.getParameter("startIndex") == null ? 1
					: Integer.valueOf(request.getParameter("startIndex")));
			Integer pageSize = (request.getParameter("pageSize") == null ? 10
					: Integer.valueOf(request.getParameter("pageSize")));
			pageNum = pageNum / pageSize + 1;
			params.put("pageNum", pageNum);
			params.put("pageSize", pageSize);

			//封装查询条件(带模糊查询)
			params.put("fuzzySearch", request.getParameter("fuzzySearch"));
			params.put("fuzzy", request.getParameter("fuzzy"));
			params.put("entity", sysUser);

			//封装页面返回数据
			PageInfo<SysUser> selectPage = sysUserService.selectPage(params);
			result.put("pageData", selectPage.getList());
			result.put("total", selectPage.getTotal());
			result.put("draw", request.getParameter("draw"));
		} catch (Exception e) {
			logger.error("用户查询失败", e);
		}
		return result;
	}

	@RequestMapping(value = "/queryUser", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public ModelAndView query(
			@RequestParam(value = "pageNum", defaultValue = PAGE_NUM) int pageNum,
			@RequestParam(value = "pageSize", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "orderBy", defaultValue = ORDERBY_NAME) String orderBy,
			SysUser sysUser) {
		ModelAndView response = new ModelAndView("/sys/admin-list");
		try {
			String[] columns = { "login_code", "user_name", "status" };
			orderBy = getSortColnum(columns, orderBy);
			PageInfo<SysUser> pageInfo = sysUserService.fuzzySelectPage(pageNum,
					pageSize, orderBy, sysUser);
			response.addObject("pageInfo", pageInfo);
		} catch (Exception e) {
			logger.error("用户查询失败", e);
		}
		return response;
	}
	
	/**
	 * 加载密码重置页面
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/loadUserResetPasswordPage", method = { RequestMethod.GET })
	@ResponseBody
	public ModelAndView loadUserResetPasswordPage() {
		return new ModelAndView("/sys/admin-reset-pwd");
	}
	
	@RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
	@ResponseBody
	public SimpleResponse resetPassword(ResetPasswordVO resetPassword){
		SimpleResponse result = new SimpleResponse();
		try {
			Session session = SecurityUtils.getSubject().getSession();
			Integer userId = Integer.parseInt(String.valueOf(session.getAttribute("userId")));
			if(userId == null || userId == 0){
				result.setState(SimpleResponse.StateEnum.ERROR.getValue());
				result.setMsg("用户未登陆");
				return result;
			}
			resetPassword.setUserId(userId);
			sysUserService.resetPassword(resetPassword);
			result.setState(SimpleResponse.StateEnum.SUCCESS.getValue());
			result.setMsg("密码重置成功");
			SecurityUtils.getSubject().logout();
		} catch (Exception e) {
			result.setState(SimpleResponse.StateEnum.ERROR.getValue());
			result.setMsg(e.getMessage());
		}
		return result;
	}
	
	@RequestMapping(value="/loadUserResource", method={RequestMethod.POST, RequestMethod.GET})
	public ModelAndView loadUserResource(Integer userId){
		return new ModelAndView("/sys/user-resource-list").addObject("resourceList", sysUserService.loadUserResource(userId));
	}
	
	@RequestMapping(value = "/loadUser", method = { RequestMethod.GET })
	@ResponseBody
	public ModelAndView load(
			@RequestParam(value = "userId", defaultValue = "0") int id) {
		ModelAndView response = new ModelAndView("/sys/admin-add");
		try {
			int userId = 0;
			SysUser user = sysUserService.selectByPrimaryKey(id);
			if (user == null) {
				user = new SysUser();
			} else {
				userId = user.getId();
			}
			List<SysUserRoleVo> roleList = sysRoleService
					.getUserRoleByUserId(userId);
			response.addObject("user", user);
			response.addObject("roleList", roleList);
		} catch (Exception e) {
			logger.error("用户加载失败", e);
		}
		return response;
	}

	@RequestMapping(value = "/addUser", method = { RequestMethod.POST })
	public String add(SysUser sysUser, Integer[] roles) {
		sysUser.setCreateDate(new Date());
		SysUser user = sysUserService.addUser(sysUser, roles);
		return "redirect:/sys/queryUser?id="+user.getId();
	}
	
	/**
	 * 校验管理员账号是否已经存在
	 * @param loginCode
	 * @return
	 */
	@RequestMapping(value="/checkUserExist", method={RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public SimpleResponse checkUserExist(String loginCode){
		SimpleResponse result = new SimpleResponse();
		List<SysUser> selectByCondition = sysUserService.selectByCondition(new SysUser(loginCode));
		if(selectByCondition != null && selectByCondition.size() > 0){
			result.setState(SimpleResponse.StateEnum.ERROR.getValue());
			result.setMsg("用户已存在");
			return result;
		}
		result.setState(SimpleResponse.StateEnum.SUCCESS.getValue());
		return result;
	}

	@RequestMapping(value = "/changeUserStatus", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public SimpleResponse changeStatus(@RequestParam(value = "userId") int id,
			int status) {
		SimpleResponse result = new SimpleResponse();
		try {
			if (status == UserStatusEnum.disable.getStatus()) {
				sysUserService.updateUserStatus(id, UserStatusEnum.disable);
			} else if (status == UserStatusEnum.enabled.getStatus()) {
				sysUserService.updateUserStatus(id, UserStatusEnum.enabled);
			} else {
				result.setMsg("用户状态未定义");
				result.setState(SimpleResponse.StateEnum.UNSIGN.getValue());
				return result;
			}
			result.putData("user", sysUserService.selectByPrimaryKey(id));
			result.setState(SimpleResponse.StateEnum.SUCCESS.getValue());
			result.setMsg("success");
		} catch (Exception e) {
			result.setMsg(e.getMessage());
			result.setState(SimpleResponse.StateEnum.ERROR.getValue());
			logger.error("用户状态修改失败", e);
		}
		return result;
	}

	@RequestMapping(value = "/delUser", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public SimpleResponse del(@RequestParam("userId") int id) {
		SimpleResponse result = new SimpleResponse();
		try {
			sysUserService.deleteByPrimaryKey(id);
			result.setState(SimpleResponse.StateEnum.SUCCESS.getValue());
			result.setMsg("success");
		} catch (Exception e) {
			result.setMsg(e.getMessage());
			result.setState(SimpleResponse.StateEnum.ERROR.getValue());
			logger.error("用户删除失败", e);
		}
		return result;
	}

}
